<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>webrtc</title>
  <link rel="stylesheet" href="./assets/css/aui-flex.css">
  <link rel="stylesheet" href="./assets/css/aui-pc.css">
  <link rel="stylesheet" href="./assets/css/aui-padding.css">
  <link rel="stylesheet" href="./assets/css/aui-margin.css">
  <style>
    .aui-but {
      width: 150px;
      line-height: 45px;
      text-align: center;
      border: 1px solid #376EFF;
      color: #376EFF;
      border-radius: 8px;
      cursor: pointer;
    }

    .aui-but.active {
      color: #fff;
      background: #376EFF;
    }

    .video-wrap {
      width: 970px;
      height: 550px;
      margin: 20px auto;
    }

    .video {
      width: 320px;
      height: 240px;
      display: block;
      float: left;
    }

    .remote-video {
      width: 320px;
      height: 240px;
      float: left;
      display: block;
      /* position: absolute;
      bottom: 0;
      right: 0; */
      /* display: none;*/
    }

    .aui-input {
      border: 1px solid #eee;
      height: 45px;
      border-radius: 4px;
      width: 300px;
      padding: 0 10px;
    }

    #userlist {
      width: 700px;
      padding-left: 20px;
    }

    #userlist li {
      line-height: 45px;
      cursor: pointer;

      border-bottom: 1px solid #ccc;
    }

    #userlist li:hover {
      background: #eee;
    }
  </style>
</head>

<body>
  <div class="aui-rel video-wrap aui-rel" id="video-wrap">
    <video src="" id="video" class="video" controls></video>

  </div>
  <div class="aui-flex aui-row-center">
    <div class="aui-but active aui-margin-r-20" id="call"> 发起视频 </div>
    <div class="aui-but" id="answer"> 接受视频 </div>
  </div>
  <div class="aui-padded-l-40">
    <input class="aui-input" type="text" placeholder="请输入用户id" id="userid">
    <div class="aui-but active aui-margin-t-10" id="saveUserid">保存用户ID </div>
  </div>
  <div>
    <p class="aui-padded-l-20 aui-padded-t-20">用户列表</p>
    <ul id="userlist">
      <li data-id=""></li>
    </ul>
  </div>
  <script src="./assets/js/peerjs.min.js"></script>
  <script src="./assets/js/socket.io.js"></script>
  <script>
    // 
    /* 

      调用涉及的API 
   let peer =  new RTCPeerConnection({
      iceServers:[]
    })

    // navigator.mediaDevices.getUserMedia
    */


    let roomid = ''
    let userId = []
    let user = ''
    let peerid = ''
    let target_peerid = ''
    let call = document.getElementById('call')
    let video = document.getElementById('video')
    // let remote_video = document.getElementById('remote-video')
    let answer = document.getElementById('answer')
    let saveUserid = document.getElementById('saveUserid')
    let userlist = document.getElementById('userlist')
    let userid_dom = document.getElementById('userid')
    let video_wrap = document.getElementById('video-wrap')


    let createVideo = function (id) {
      if (id && !document.getElementById(id)) {

        let video = document.createElement('video')
        video.classList = 'remote-video';
        video.id = id;
        video.src = '';
        video.controls = true;
        video_wrap.appendChild(video)
        return video


      }

    }

    var peer = new Peer({
      host: '127.0.0.1',
      port: 9100,
      path: "/peer-server",
    });
    let getStream = async () => {
      var getUserMedia = navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
      let stream = await getUserMedia({
        video: true,
        audio: true
      });
      return stream;
    }

    saveUserid.onclick = function () {
      if (userid_dom.value) {
        localStorage.setItem('user', userid_dom.value)
        user = userid_dom.value
      }
    }
    userlist.onclick = function (ev) {
      // console.log(ev.target.innerHTML);

      target_peerid = ev.target.getAttribute('data-id')
    }
    if (localStorage.getItem('user')) {
      user = localStorage.getItem('user')
      userid_dom.value = user
    }


    let socket = io('http://10.10.111.188:3001')
    // let socket = io('http://127.0.0.1:3001')


    socket.on('connectionSuccess', function (id) {
      console.log(id);
      if (id) {
        roomid = id
      }
    })

    socket.on('4', function () {
      console.log('2121');
    })
    socket.on('getRoom', function (ids) {
      try {
        console.log(ids)
        let data = JSON.parse(ids)
        let str = ''
        Object.keys(data).forEach(key => {
          if (data[key] != peerid) {
            str += `<li data-id="${data[key]}"> ${key}</li>`
          }
        })
        userlist.innerHTML = str

      } catch (e) {
        console.log(e);
      }
    })
    socket.on('acceptCall', function () {
      console.log('acceptCall');
    })

    call.onclick = async function () {

      if (target_peerid) {
        socket.emit('callRemote', { peerid: target_peerid })
        let stream = await getStream()
        var call = peer.call(target_peerid, stream);
        video.srcObject = stream
        video.play()
        call.on('stream', function (remoteStream) {
          let remote_video = createVideo(remoteStream.id);
          console.log('remote_video --call');
          if (remote_video) {
            remote_video.srcObject = remoteStream
            // remote_video.play()
          }

        });

      } else {
        alert('请选择用户')
      }


    }

    peer.on('call', async function (call) {
      let stream = await getStream()
      video.srcObject = stream
      call.answer(stream);
      console.log('call');
      call.on('stream', function (remoteStream) {
        let remote_video = createVideo(remoteStream.id);
        console.log('remote_video');
        if (remote_video) {
          remote_video.srcObject = remoteStream
          // remote_video.play()
        }
      });
    });
    peer.on('open', function (id) {
      console.log('id', id);
      peerid = id;
      var conn = peer.connect(id);
      socket.emit('joinRoom', { user, id })
      conn.on('open', function () {
        // Receive messages
        conn.on('data', function (data) {
          console.log('Received', data);
        });
        // Send messages
        conn.send('Hello!');
      });
    })


    peer.on('connection', function (conn) {
      conn.on('data', function (data) {
        // Will print 'hi!'
        console.log(data);
      });
    });








  </script>
</body>

</html>